package com.leyou.order.service;

import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.locals.UserHolder;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.utils.IdWorker;
import com.leyou.item.client.ItemClient;
import com.leyou.item.dto.SkuDTO;
import com.leyou.order.dto.CartDTO;
import com.leyou.order.dto.OrderDTO;
import com.leyou.order.enmus.OrderStatusEnum;
import com.leyou.order.entity.Order;
import com.leyou.order.entity.OrderDetail;
import com.leyou.order.entity.OrderLogistics;
import com.leyou.order.mapper.OrderDetailMapper;
import com.leyou.order.mapper.OrderLogisticsMapper;
import com.leyou.order.mapper.OrderMapper;
import com.leyou.order.util.PayHelper;
import com.leyou.order.vo.OrderDetailVO;
import com.leyou.order.vo.OrderLogisticsVO;
import com.leyou.order.vo.OrderVO;
import com.leyou.user.client.UserClient;
import com.leyou.user.dto.AddressDTO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 虎哥
 */
@Service
public class OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderLogisticsMapper logisticsMapper;

    @Autowired
    private OrderDetailMapper detailMapper;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private ItemClient itemClient;

    @Autowired
    private UserClient userClient;

    @Transactional
    public Long createOrder(OrderDTO orderDTO) {
        // 1.新增订单
        Order order = new Order();
        // 1.1.订单id
        long orderId = idWorker.nextId();
        order.setOrderId(orderId);
        // 1.2.订单金额
        List<CartDTO> carts = orderDTO.getCarts();
        // 1.2.1.获取商品id
        List<Long> idList = carts.stream().map(CartDTO::getSkuId).collect(Collectors.toList());
        // 1.2.2.查询商品
        List<SkuDTO> skuList = itemClient.querySkuByIds(idList);
        // 1.2.3.得到sku及数量的map
        Map<Long, Integer> skuMap = carts.stream().collect(Collectors.toMap(CartDTO::getSkuId, CartDTO::getNum));
        // 1.2.4.准备detail的集合
        List<OrderDetail> detailList = new ArrayList<>(skuList.size());
        // 1.2.5.计算总价
        long total = 0L;
        for (SkuDTO sku : skuList) {
            // 获取数量，计算总价
            Integer num = skuMap.get(sku.getId());
            total += sku.getPrice() * num;
            // 封装OrderDetail
            OrderDetail detail = new OrderDetail();
            detailList.add(detail);
            detail.setTitle(sku.getTitle());
            detail.setSkuId(sku.getId());
            detail.setPrice(sku.getPrice());
            detail.setNum(num);
            detail.setOwnSpec(sku.getOwnSpec());
            detail.setImage(StringUtils.substringBefore(sku.getImages(), ","));
            detail.setOrderId(orderId);
        }
        order.setTotalFee(total);
        order.setPaymentType(orderDTO.getPaymentType());
        order.setPostFee(0L);
        order.setActualFee(order.getTotalFee() + order.getPostFee());
        // 1.3.用户
        Long userId = UserHolder.getUser().getId();
        order.setUserId(userId);
        // 1.4.状态
        order.setStatus(OrderStatusEnum.INIT.value());

        // 1.5.写入数据库
        orderMapper.insertSelective(order);

        // 2.新增订单详情
        detailMapper.insertList(detailList);

        // 3.新增订单物流
        // 3.1.获取addressId
        Long addressId = orderDTO.getAddressId();
        // 3.2.根据id查询物流收件人信息
        AddressDTO addressDTO = userClient.queryAddressById(userId, addressId);
        // 3.3.封装为OrderLogistics类型
        OrderLogistics logistics = BeanHelper.copyProperties(addressDTO, OrderLogistics.class);
        logistics.setOrderId(orderId);
        // 3.4.写入数据库
        logisticsMapper.insertSelective(logistics);

        // 4.减库存
        try {
            itemClient.minusStock(skuMap);
        } catch (Exception e) {
            throw new LyException(ExceptionEnum.STOCK_NOT_ENOUGH);
        }
        return orderId;
    }

    public OrderVO queryById(Long orderId) {
        // 1.查询订单
        Order order = orderMapper.selectByPrimaryKey(orderId);
        if (order == null) {
            throw new LyException(ExceptionEnum.ORDER_NOT_FOUND);
        }
        OrderVO orderVO = BeanHelper.copyProperties(order, OrderVO.class);
        // 2.查询订单详情
        orderVO.setDetailList(queryDetailByOrderId(orderId));
        // 3.查询订单物流
        orderVO.setLogistics(queryLogisticsByOrderId(orderId));
        return orderVO;
    }

    private OrderLogisticsVO queryLogisticsByOrderId(Long orderId) {
        OrderLogistics logistics = logisticsMapper.selectByPrimaryKey(orderId);
        if (logistics == null) {
            throw new LyException(ExceptionEnum.ORDER_NOT_FOUND);
        }
        return BeanHelper.copyProperties(logistics, OrderLogisticsVO.class);
    }

    private List<OrderDetailVO> queryDetailByOrderId(Long orderId) {
        OrderDetail record = new OrderDetail();
        record.setOrderId(orderId);
        List<OrderDetail> list = detailMapper.select(record);
        if (CollectionUtils.isEmpty(list)) {
            throw new LyException(ExceptionEnum.ORDER_NOT_FOUND);
        }
        return BeanHelper.copyWithCollection(list, OrderDetailVO.class);
    }

    @Autowired
    private PayHelper payHelper;

    public String queryPayUrl(Long orderId) {
        // TODO 加缓存
        // 查询订单
        Order order = orderMapper.selectByPrimaryKey(orderId);
        if (order == null) {
            throw new LyException(ExceptionEnum.ORDER_NOT_FOUND);
        }
        // 判断订单状态，只有未支付订单，才需要查询支付地址
        if (!Objects.equals(order.getStatus(), OrderStatusEnum.INIT.value())) {
            // 订单状态不正确
            throw new LyException(ExceptionEnum.INVALID_ORDER_STATUS);
        }
        // 获取支付地址
        return payHelper.getPayUrl(orderId, order.getActualFee());
    }

    @Transactional
    public void handleNotify(Map<String, String> data) {
        // 校验业务结果
        payHelper.checkResult(data);
        // 校验签名
        payHelper.checkSignature(data);
        // 校验订单金额
        String total_fee = data.get("total_fee");
        String out_trade_no = data.get("out_trade_no");
        if (StringUtils.isBlank(total_fee) || StringUtils.isBlank(out_trade_no)) {
            throw new LyException(ExceptionEnum.INVALID_PARAM_ERROR);
        }
        Long orderId = Long.valueOf(out_trade_no);
        Order order = orderMapper.selectByPrimaryKey(orderId);
        if (!total_fee.equals(order.getActualFee().toString())) {
            throw new LyException(ExceptionEnum.INVALID_PARAM_ERROR);
        }
        // 校验幂等性
        if (!Objects.equals(order.getStatus(), OrderStatusEnum.INIT.value())) {
            // 订单状态已支付，说明是重复通知
            return;
        }
        // 修改订单状态, 乐观锁 update tb_order set status = 2 where order_id = 1241214 AND status = 1
        Order record = new Order();
        record.setStatus(OrderStatusEnum.PAY_UP.value());
        record.setPayTime(new Date());

        Example example = new Example(Order.class);
        example.createCriteria().andEqualTo("orderId", orderId).andEqualTo("status", 1);

        int count = orderMapper.updateByExampleSelective(record, example);
        if (count != 1) {
            throw new RuntimeException("更新失败！");
        }
    }

    public Integer queryPayStatus(Long orderId) {
        Order order = orderMapper.selectByPrimaryKey(orderId);
        if(order == null){
            throw new LyException(ExceptionEnum.ORDER_NOT_FOUND);
        }
        return order.getStatus();
    }
}
